package com.jweb.framework.http;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import com.jweb.framework.core.CoreRuntimeException;
import com.jweb.framework.http.interceptors.HttpStreamResolver;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：流解析
 */
public class ContentLengthResolver implements HttpStreamResolver {
	
	private boolean useContentLength = true ;
	
	public void setUseContentLength(boolean useContentLength){
		this.useContentLength = useContentLength ;
	}
	
	public Object resolve(HttpServletRequest request) throws CoreRuntimeException {
		if(this.useContentLength){
			int i = request.getContentLength();
			if(i <= 0){
				throw new CoreRuntimeException("JAVAHT0033" , new String[]{request.getMethod()} , "contentLength is <=0 , http-method: " + request.getMethod()) ;
			}
			try {
				return invokeByte(request.getInputStream() , i) ;
				//return invokeByte(request.getInputStream());
			} catch (IOException e) {
				throw new CoreRuntimeException("JAVAHT0034" , "http_stream_read_err" , e);
			}
		}
		
		try {
			return invokeByte(request.getInputStream());
		} catch (Exception e) {
			throw new CoreRuntimeException("JAVAHT0034" , "http_stream_read_err" , e);
		}
	}
	
	
	private Object invokeByte(ServletInputStream inputStream) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream(64);
			byte[] bytes = new byte[512];
			int i ;
			
			while((i = inputStream.read(bytes)) >= 0){
				if(i > 0){
					baos.write(bytes , 0 , i);
				}
			}
			
			return baos.toByteArray();
		} catch (Exception e) {
			throw new CoreRuntimeException("JAVAHT0034" , "http_stream_read_err" , e);
		}
	}
	
	private Object invokeByte(InputStream inputStream , int i) {
		try {
			DataInputStream dis = new DataInputStream(inputStream);
			//inputStream.mark(0);
			byte[] bytes = new byte[i];
			while (inputStream.read(bytes) != -1) {
				//System.out.println(bytes);
			}
			/*byte[] bytes = new byte[i];
			dis.readFully(bytes);*/
			
			return bytes ;
		} catch (Exception e) {
			throw new CoreRuntimeException("JAVAHT0034" , "http_stream_read_err" , e);
		}
	}
	
}
